package open.panxiong.shared.http.controller

import android.content.Context
import fi.iki.elonen.NanoHTTPD.IHTTPSession
import fi.iki.elonen.NanoHTTPD.Response
import fi.iki.elonen.NanoHTTPD.getMimeTypeForFile
import fi.iki.elonen.NanoHTTPD.newFixedLengthResponse
import open.panxiong.shared.http.annotation.NanohttpdApi
import open.panxiong.shared.http.config.ConstConfig
import open.panxiong.shared.http.model.NanohttpdResponse
import open.panxiong.shared.util.generateCover
import open.panxiong.shared.util.isVideoFile
import java.io.FileInputStream
import java.net.URLDecoder

class VideoController {

    // 获取视频封面
    @NanohttpdApi("/api/get-video-cover")
    fun getVideoCover(context: Context, session: IHTTPSession): Response {
        try {
            var filename = session.parameters["filename"]?.last()
            if (filename.isNullOrEmpty()) {
                return NanohttpdResponse(code = -1, msg = "文件名错误").toJson()
            }
            filename = URLDecoder.decode(filename, Charsets.UTF_8.name())

            val file = ConstConfig.getShareFileValue(context, filename)

            if (!file.exists() || !file.isFile || !isVideoFile(file.name)) {
                return NanohttpdResponse().to404()
            }
            val coverFile = ConstConfig.getTempFileValue(context, file.name)
            if (!coverFile.exists()) {
                if (!generateCover(file, coverFile, 150, 60)) {
                    return NanohttpdResponse().to500("生成缩略图失败")
                }
            }

            val response = newFixedLengthResponse(
                Response.Status.OK,
                getMimeTypeForFile(coverFile.name),
                FileInputStream(coverFile),
                coverFile.length()
            )
            return response
        } catch (e: Exception) {
            return NanohttpdResponse().to500(e.message.toString())
        }
    }

}